﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;
using System.Xml.Serialization;
using System.Net;
using System.Net.Sockets;
using WhiteBoard;
using LumiSoft.Net.UDP;
using LumiSoft.Net.Codec;
using System.Threading;
using WinSound.Media.Wave;

namespace WFFS
{   
    public partial class Form1 : Form
    {
        public static string SQLCONNSTR = System.Configuration.ConfigurationManager.AppSettings["connectionstring"];
        public SqlConnection dbConnect;
        public SqlConnection dbThreadConnect;

        public FrmSound frmSound;

        FrmMenu frmMenu = null;
        public FrmMsg frmMsg = null;
        public string LocalIP;
        //1
        delegate void MsgRef(string msg);
        AsySocket listener = null;
        public string MyName;
        public AsySocket socket = null;
        public SortedList<string, AsySocket> clients = new SortedList<string, AsySocket>();
        public Form1()
        {
            InitializeComponent();
            initForm();  //李万峰             
            FormInit(); //肖军
            InitAudio(); //冯曦
            Init(); //初始化广播
            InitUdpCall(); //单点对话

            this.WindowState = FormWindowState.Maximized;
           
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //连接指挥中心
            InfoConnectServer();

            if (frmMenu == null)
            {
                frmMenu = new FrmMenu(this);
                frmMenu.Show();
            }
            frmMenu.TopMost = true;
            frmMenu.Location = new Point(this.Width - 320, 150);
            //pbZoom.Location = new Point(this.Width - 110, this.Height - 450);


            if (frmMsg == null)
            {
                frmMsg = new FrmMsg();
            }
            else if (frmMsg.Text == "")
            {
                frmMsg.Dispose();
                frmMsg = null;
                frmMsg = new FrmMsg();
            }
            frmMsg.Show();
            frmMsg.Location = new Point(500, 350);
            frmMsg.TopMost = true;
            frmMsg.Hide();
        }
        //窗口最大化与正常情况的切换
        private void button1_Click(object sender, EventArgs e){
            if (this.WindowState == FormWindowState.Maximized)
            {
                //方便测试用
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
                this.KeyPreview = false;
                this.ShowInTaskbar = true;
                this.ControlBox = true;
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                //this.WindowState = FormWindowState.Maximized;
                this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
                this.BackColor = System.Drawing.Color.Black;
                //this.ClientSize = new System.Drawing.Size(1920, 1080);
                this.ControlBox = false;
                //this.Controls.AddRange(new System.Windows.Forms.Control[] { this.picture1, this.word });
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                this.KeyPreview = true;
                this.MaximizeBox = false;
                this.Name = "screen";
                this.ShowInTaskbar = false;
                this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
                this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            }
        }
        #region 李万峰代码
        //////////////////////////////////李万峰代码//////////////////////////////////////////////
        //定义窗体级公用变量 
        public string role = ConfigurationManager.AppSettings["role"];//当前平板的角色
        DShapeList drawingList = new DShapeList();							//图元
        DShapeList drawingListUndo = new DShapeList();						//撤销图形保存
        public String path;//图片背景
        //临时变量
        private GraphicsPath mousePath;
        Point startPoint, endPoint; //开始画线的起点坐标，此变量的值将在MOUSEDOWN事件中确定 
        public Color drawColor = Color.FromArgb(0, 0, 0);//选择的颜色
        public int lineWidth = 4;//线宽度
        public ImageType newType = ImageType.Empt;
        public Button selectButton;//被选中的图标
        public int ishuiShan=0;//是否会商状态；1为是
        //表单初始化
        public void initForm()
        {

            this.Drawing.Paint += new System.Windows.Forms.PaintEventHandler(this.Drawing_Paint);
            //控件要能拖动必须设置控件的AllowDrop=true
            this.Drawing.AllowDrop = true;
            this.a1.AllowDrop = true;
            this.b1.AllowDrop = true;
            this.c1.AllowDrop = true;
            stop_soket.Enabled = false;
            // 这句代码就是说在这个类中我们不检查跨线程的调用是否合法
            Control.CheckForIllegalCrossThreadCalls = false;
            if (role.Equals("1"))
            {
                //画图
                this.Drawing.MouseDown += new MouseEventHandler(Drawing_MouseDown);
                this.Drawing.MouseMove += new MouseEventHandler(Drawing_MouseMove);
                this.Drawing.MouseUp += new MouseEventHandler(Drawing_MouseUp);
                //拖拽
                this.Drawing.DragDrop += new System.Windows.Forms.DragEventHandler(this.Drawing_DragDrop);
                this.Drawing.DragEnter += new System.Windows.Forms.DragEventHandler(this.Drawing_DragEnter);
                toolStrip_Client.Visible = false;
            }
            else if (role.Equals("2"))
            {
                toolStrip_image.Visible = false;
            }
            networkTimer.Start();
        }

        //弹出会商选择界面
        FrmNegotiation frmNegotiation;
        private void toolStripButton14_Click(object sender, EventArgs e)
        {
            if (frmNegotiation == null)
            {
                frmNegotiation = new FrmNegotiation(this);
            }
            else if (frmNegotiation.Text == "")
            {
                frmNegotiation.Dispose();
                frmNegotiation = null;
                frmNegotiation = new FrmNegotiation(this);
            }
            frmNegotiation.Show();
            string x = ReadIniData("FrmNegotiation", "X", "X", Application.StartupPath + @"\WFFS.ini");
            string y = ReadIniData("FrmNegotiation", "Y", "Y", Application.StartupPath + @"\WFFS.ini");
            frmNegotiation.Location = new Point(int.Parse(x), int.Parse(y));
            frmNegotiation.TopMost = true;
        }
      
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }
        //客户端是否允许会商画图
        //声明委托类型  必须委托 不然不能调用FORM中的控件
        public delegate void InvokeDrawImage(DrawImage drawImage);
        public void DrawImage(DrawImage d)
        {
            //跨线程的控件操作，需要使用委托
            if (this.InvokeRequired)
            {
                //实例化委托
                InvokeDrawImage id = new InvokeDrawImage(this.DrawImage);
                this.Invoke(id, new object[] { d });
                return;
            }
            if (d.isdraw)
            {
                ishuiShan = 1;
                //画图
                this.Drawing.MouseDown += new MouseEventHandler(Drawing_MouseDown);
                this.Drawing.MouseMove += new MouseEventHandler(Drawing_MouseMove);
                this.Drawing.MouseUp += new MouseEventHandler(Drawing_MouseUp);
                //拖拽
                this.Drawing.DragDrop += new System.Windows.Forms.DragEventHandler(this.Drawing_DragDrop);
                this.Drawing.DragEnter += new System.Windows.Forms.DragEventHandler(this.Drawing_DragEnter);
                toolStrip_image.Visible = true;
                if (role.Equals("2")){
                　stop_soket.Visible = false;
                }
                //所有拖动控件移开拖动事件
                foreach (Control Item in this.Drawing.Controls)
                {
                    if (Item is Button)
                    {
                        Item.MouseDown += new MouseEventHandler(UiMove_MouseDown);
                        Item.MouseMove += new MouseEventHandler(UiMove_MouseMove);
                        Item.MouseUp += new MouseEventHandler(UiMove_MouseUp);
                    }
                }
                MessageBox.Show("指挥中心发起会商！");
            }
            else
            {
                ishuiShan =0;
                //移除画图
                this.Drawing.MouseDown -= new MouseEventHandler(Drawing_MouseDown);
                this.Drawing.MouseMove -= new MouseEventHandler(Drawing_MouseMove);
                this.Drawing.MouseUp -= new MouseEventHandler(Drawing_MouseUp);
                //移除拖拽
                this.Drawing.DragDrop -= new System.Windows.Forms.DragEventHandler(this.Drawing_DragDrop);
                this.Drawing.DragEnter -= new System.Windows.Forms.DragEventHandler(this.Drawing_DragEnter);
                toolStrip_image.Visible = false;
                //所有拖动控件移开拖动事件
                foreach (Control Item in this.Drawing.Controls)
                {
                    if (Item is Button) {
                        Item.MouseDown -= new MouseEventHandler(UiMove_MouseDown);
                        Item.MouseMove -= new MouseEventHandler(UiMove_MouseMove);
                        Item.MouseUp -= new MouseEventHandler(UiMove_MouseUp);
                    
                    }
                }
                MessageBox.Show("指挥中心移除会商!");
            }
        }

        //接收全息指令
        public delegate void InvokeallDirective(WBMsgAllDirective wBMsgAllDirective);
        public void allDirective(WBMsgAllDirective wBMsgAllDirective)
        {  //跨线程的控件操作，需要使用委托
            if (this.InvokeRequired)
            {
                //实例化委托
                InvokeallDirective id = new InvokeallDirective(this.allDirective);
                this.Invoke(id, new object[] { wBMsgAllDirective });
                return;
            }
            whenAlldirective(wBMsgAllDirective.im, wBMsgAllDirective.name);
            this.frmMsg.GetPicInfo();
            this.frmMenu.changeBtn("btnJSXX", "1");
         //   MemoryStream ms = new MemoryStream(wBMsgAllDirective.im);
          //  Image img = Image.FromStream(ms, true);//在这里出错   
            //流用完要及时关闭   
          //  ms.Close();
           
        }


        //设置线的宽度
        private void setlineWidth(object sender, EventArgs e)
        {
            ToolStripDropDownItem buton = (ToolStripDropDownItem)sender; //xiaojun
            //ToolStripButton buton = (ToolStripButton)sender;
            setlineWidth(buton.Text);
            SetPen(this.drawColor, this.lineWidth);
        }
        /// <summary>
        /// 设置线宽
        /// </summary>
        /// <param name="text"></param>
        private void setlineWidth(String text)
        {
            lineWidth = int.Parse(text);
        }
        /// <summary>
        /// 画图事件
        /// </summary>		
        private void Drawing_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            Graphics displayGraphics = e.Graphics;
            //Graphics displayGraphics=this.Drawing.CreateGraphics();
            switch (newType)
            {
                case ImageType.Path:
                    if (mousePath != null)
                    {
                        displayGraphics.DrawPath(new Pen(drawColor, lineWidth), mousePath);
                    }
                    break;
                case ImageType.Pick:
                    break;
            }
            drawingList.DrawList(displayGraphics);
        }

        //设置画图风格
        public void SetPen(Color drawColor, int lineWidth)
        {
            whenSetPen(drawColor, lineWidth);
            if (netWork != null)
            {
                WBMsgDrawStyle drawStyle = new WBMsgDrawStyle();
                drawStyle.drawColor = drawColor;
                drawStyle.lineWidth = lineWidth;
                netWork.SendWBMsgConnectedHdlr(drawStyle);
            }
        }

        //当设置画图风格
        public void whenSetPen(Color drawColor, int lineWidth)
        {
            this.drawColor = drawColor;
            this.lineWidth = lineWidth;
        }
        //清除显示
        public void clearScreen()
        {
            drawingList = new DShapeList();
            drawingListUndo = new DShapeList();
            //清除控件           
            List<Control> list = new List<Control>();
            foreach (Control Item in this.Drawing.Controls)
            {
                list.Add(Item);
            }
            int size = this.Drawing.Controls.Count;
            for (int i = 0; i < size; i++)
            {
                this.Drawing.Controls.Remove(list[i]);
            }
            Drawing.Invalidate();
        }
        //删除图标（button）
        private void deleteButton(object sender, EventArgs e)
        {
            if (this.selectButton != null)
            {
                WhenUiDelete(selectButton.Name);
                if (netWork != null)
                {
                    enWBDeleteButton enWBDeleteButton = new enWBDeleteButton();
                    enWBDeleteButton.name = selectButton.Name;
                    netWork.SendWBMsgConnectedHdlr(enWBDeleteButton);
                }
            }
        }
        //当删除图标（button）
        public void WhenUiDelete(String name)
        {
            Control control = GetControl(name, this.Drawing);
            if (control == null) return;
            this.Drawing.Controls.Remove(control);
        }
        //画图，当鼠标按下
        public void WhenMouseDown(Point pt)
        {
            //鼠标按下确定起点的坐标，把这个变量赋于STARTPOINT值 
            startPoint = pt;
            newType = ImageType.Path;
            switch (newType)
            {
                case ImageType.Path:
                    mousePath = new GraphicsPath();
                    mousePath.AddLine(pt, pt);
                    break;
            }
        }
        //画图，当鼠标移动
        public void WhenMouseMove(Point pt)
        {
            switch (newType)
            {
                case ImageType.Path:
                    mousePath.AddLine(pt, pt);
                    break;
            }
            Drawing.Invalidate();
        }
        //画图，当鼠标抬起
        public void WhenMouseUp(Point pt)
        {
            endPoint = pt;
            switch (newType)
            {
                case ImageType.Path:
                    drawingList.Add(new DPath(mousePath, drawColor, lineWidth));
                    mousePath = null;
                    break;
            }
            newType = ImageType.Text;
            Drawing.Invalidate();
        }
        //画图，撤消
        public void WhenBack()
        {
            if (drawingList.Count == 0)
                return;
            drawingListUndo.Add(drawingList[drawingList.Count - 1]);
            drawingList.RemoveAt(drawingList.Count - 1);
            Drawing.Invalidate();
        }
        //画图，恢复
        public void WhenProceed()
        {
            if (drawingListUndo.Count == 0)
                return;
            drawingList.Add(drawingListUndo[drawingListUndo.Count - 1]);
            drawingListUndo.RemoveAt(drawingListUndo.Count - 1);
            Drawing.Invalidate();
        }
        private void Drawing_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                WhenMouseDown(new Point(e.X, e.Y));
                WhenMouseSentToPeers("down", new Point(e.X, e.Y));
            }
        }
        private void Drawing_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                switch (newType)
                {
                    case ImageType.Path:
                        WhenMouseMove(new Point(e.X, e.Y));
                        WhenMouseSentToPeers("move", new Point(e.X, e.Y));
                        break;
                }

            }
        }
        private void Drawing_MouseUp(object sender, MouseEventArgs e)
        {
            switch (newType)
            {
                case ImageType.Path:
                    WhenMouseUp(new Point(e.X, e.Y));
                    WhenMouseSentToPeers("up", new Point(e.X, e.Y));
                    break;
            }

        }

        private void color_Click(object sender, System.EventArgs e)
        {
            //ToolStripButton buton = (ToolStripButton)sender;
            //drawColor = buton.BackColor;
            ToolStripDropDownItem buton = (ToolStripDropDownItem)sender; //xiaojun            
            System.Drawing.ColorConverter cc = new ColorConverter();
            drawColor = (Color)cc.ConvertFromString(buton.Name);
            SetPen(drawColor, this.lineWidth);
        }
        private void MoreColor_Click(object sender, System.EventArgs e)
        {
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                drawColor = colorDialog.Color;
                SetPen(drawColor, this.lineWidth);
            }
        }

        /// <summary>
        /// 后退
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void back_Click(object sender, EventArgs e)
        {
            WhenBack();
            if (netWork != null)
            {
                WBMsgBack wBMsgBack = new WBMsgBack();
                netWork.SendWBMsgConnectedHdlr(wBMsgBack);
            }
        }
        /// <summary>
        /// 前进
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void proceed_Click(object sender, EventArgs e)
        {
            WhenProceed();
            if (netWork != null)
            {
                WBMsgProceed wBMsgProceed = new WBMsgProceed();
                netWork.SendWBMsgConnectedHdlr(wBMsgProceed);
            }
        }
        //设置图片  
        public void setImage(WBMsgDrawingImage wBMsgDrawingImage)
        {
            whenSetImage(wBMsgDrawingImage);
            if (netWork != null)
            {
                netWork.SendWBMsgConnectedHdlr(wBMsgDrawingImage);
            }
        }

        public void whenSetImage(WBMsgDrawingImage DrawingImage){
        
            if (DrawingImage.type.Equals("cat"))
            { //切图
                MemoryStream MS = new MemoryStream(DrawingImage.im);
                Bitmap image = new System.Drawing.Bitmap(MS);
                this.Drawing.Image = Util.update_Size(image, this.Drawing.Width, this.Drawing.Height);
            }
            else
            {
                this.path = DrawingImage.path;
                this.Drawing.Image = new Bitmap(Application.StartupPath + "\\" + path);
            }

        }
        //消防车按下事件
        public void carDrafting_MouseDown(object sender, MouseEventArgs e)
        {
            string btnname = ((Control)sender).Name;
            string rfid = (btnname.Split(','))[1];
            newType = ImageType.carDrafting;
            Control control = (Control)sender;
            UiDrafting_MouseDown(control.Text, control.Name.Split(',')[0]);
        }
        //人员拖动，鼠标按下
        public void userDrafting_MouseDown(object sender, MouseEventArgs e)
        {
            newType = ImageType.carDrafting;
            ListView view = (ListView)sender;
            try
            {
                String str = view.SelectedItems[0].Text;
                UiDrafting_MouseDown(str, "users");
            }
            catch (Exception er)
            {
            }

        }
        //图片按下事件
        private void imageDrafting_MouseDown(object sender, MouseEventArgs e)
        {
            newType = ImageType.carDrafting;
            //ToolStripButton buton = (ToolStripButton)sender;
            ToolStripDropDownItem buton = (ToolStripDropDownItem)sender; //xiaojun
            UiDrafting_MouseDown(buton.Name, "imgOrder");
        }
        private void Drawing_DragDrop(object sender, DragEventArgs e)
        {
            if (newType == ImageType.carDrafting)
            {
                Control control = (Control)sender;
                String text = e.Data.GetData(DataFormats.Text).ToString();
                Point p = control.PointToClient(Control.MousePosition); //点P是相对于画图控件坐标
                Random ran = new Random();
                int RandKey = ran.Next(100, 999);
                string name = "bushu" + RandKey;
                UiDraftingControl_DragDrop(name, text, p);
                if (netWork != null)
                {
                    Point tm = role.Equals("1") ? Common.reduce(p) : Common.amplify(p);
                    WBMsgUiDrafting_DragDrop uiDrafting_DragDrop = new WBMsgUiDrafting_DragDrop();
                    uiDrafting_DragDrop.name = name;
                    uiDrafting_DragDrop.text = text;
                    uiDrafting_DragDrop.p = tm;
                    netWork.SendWBMsgConnectedHdlr(uiDrafting_DragDrop);
                }
            }
        }
        private void Drawing_DragEnter(object sender, DragEventArgs e)
        {
            if (newType == ImageType.carDrafting)
            {
                UiDraftingControl_DragEnter(e);
            }
        }

   
        /////////////////////////////////////////////控件拖动<将控件拖动到另一个容器内>//////////////////////////////////////////////////
        //拖放事件
        //名称 说明
        //DragEnter 当用户在拖放操作过程中首次将鼠标光标拖到控件上时，会引发该事件
        //DragDrop 在完成拖放操作时发生
        //GiveFeedback 在执行拖动操作期间发生
        //DragLeave 如果用户移出一个窗口，则引发DragLeave事件
        //DragOver 如果鼠标移动但停留在同一个控件中，则引发DragOver事件
        //QueryContinueDrag 在拖放操作过程中，当键盘或鼠标按钮状态发生变化时，会引发QueryContinueDrag 事件。QueryContinueDrag事件允许拖动源确定是否应取消拖放操作

        //要拖动的控件的 MouseDown事件
        public void UiDrafting_MouseDown(String title, String type)
        {
            this.a1.DoDragDrop(title + "," + type, DragDropEffects.Copy);
            /**
           public DragDropEffects DoDragDrop ( Object sender,DragDropEffects allowedEffects)
           data：用户所要拖动的数据内容。必须将所要拖动的内容传入到这个方法的第一个参数位置。
           allowedEffects：DragDropEffects枚举值之一，此类型包含了拖动操作的效果。DragDropEffects枚举值如表32.8所示。
           DragDropEffects枚举值：
             枚举值 说明
             All 从拖动源复制、移除数据，并将其滚动到放置目标中
             Copy 将数据复制到放置目标
             Link 将拖动源中的数据链接到放置目标
             Move 将拖动源的数据移动到放置目标
             None 放置目标不接受该数据
             Scroll 即将在放置目标中开始滚动，或当前正在滚动
           开发人员在使用DoDragDrop方法时，必须指定参数allowedEffects为表中的任何一个成员，另外，还可以使用位运算符，把其中的任何一个成员作为一个完整参数传入，以得到所需的拖动效果，实现关键代码如下：
             DragDropEffects.Copy| DragDropEffects.None**/
        }
        //控件拖动到控件的 DragEnter事件
        public void UiDraftingControl_DragEnter(DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }


        //声明委托类型
        public delegate void InvokeDele(String name, String text, Point p);
        //控件拖动到控件的 DragDrop事件
        public void UiDraftingControl_DragDrop(String name, String text, Point p)
        {
            //跨线程的控件操作，需要使用委托
            if (this.InvokeRequired)
            {
                //实例化委托
                InvokeDele id = new InvokeDele(this.UiDraftingControl_DragDrop);
                this.Invoke(id, new object[] { name, text, p });
                return;
            }
            Control control = this.Drawing;
            // 取得被拖放的项       
            Button tuttontemp = new Button();
            tuttontemp.Name = name;
            tuttontemp.TextAlign = ContentAlignment.BottomCenter;
            tuttontemp.BackgroundImageLayout = ImageLayout.Center;
            if ((text.Split(','))[1].Equals("car"))
            {//车辆
                tuttontemp.BackgroundImage = new Bitmap(Application.StartupPath + "\\bushutu\\car3.png");
                tuttontemp.Text = (text.Split(','))[0];
            }
            else if ((text.Split(','))[1].Equals("duanhao"))
            {//段号
                String[] tishi = text.Split(',')[0].Split(';');
                tuttontemp.BackgroundImage = new Bitmap(Application.StartupPath + "\\bushutu\\d" + tishi[0] + ".png");
                tuttontemp.Text = tishi[1];// +":" + tishi[2];
            }
            else if ((text.Split(','))[1].Equals("imgOrder"))
            {//图标命令
                tuttontemp.BackgroundImage = new Bitmap(Application.StartupPath + "\\bushutu\\" + (text.Split(','))[0] + ".png");
            }
            else
            {//人员
                tuttontemp.BackgroundImage = new Bitmap(Application.StartupPath + "\\bushutu\\001.png");
                tuttontemp.Text = (text.Split(','))[0];
            }
            tuttontemp.Location = p;
            control.Controls.Add(tuttontemp);
            Size size = tuttontemp.BackgroundImage.Size;
            size.Width = size.Width + 7;
            size.Height = size.Height + 7;
            tuttontemp.Size = size;
            tuttontemp.AllowDrop = true;
            if (role.Equals("1") || ishuiShan==1)
            {
                tuttontemp.MouseDown += new MouseEventHandler(UiMove_MouseDown);
                tuttontemp.MouseMove += new MouseEventHandler(UiMove_MouseMove);
                tuttontemp.MouseUp += new MouseEventHandler(UiMove_MouseUp);
            }
            this.selectButton = tuttontemp;
        }
        /////////////////////////////////////////////控件移动<控件在对应的容器内移动>//////////////////////////////////////////////////
        //
        bool bDragging = false;//是否移动的变量
        Point mouse_offset;//开始位置
        private void UiMove_MouseDown(object sender, MouseEventArgs e)
        {
            this.selectButton = ((Button)sender);
            whenUiMove_MouseDown(new Point(-e.X, -e.Y));
            if (netWork != null)
            {
                Point p = new Point(-e.X, -e.Y);
                Point tm = role.Equals("1") ? Common.reduce(p) : Common.amplify(p);
                WBMsgUiMove_MouseDown msgUiMove_MouseDown = new WBMsgUiMove_MouseDown();
                msgUiMove_MouseDown.p = tm;
                netWork.SendWBMsgConnectedHdlr(msgUiMove_MouseDown);
            }
        }
        public void whenUiMove_MouseDown(Point p)
        {
            bDragging = true;
            mouse_offset = p;
        }
        private void UiMove_MouseMove(object sender, MouseEventArgs e)
        {
            String name = ((Control)sender).Name;
            //设置拖动时鼠标箭头
            ((Control)sender).Cursor = Cursors.Arrow;
            whenUiMove_MouseMove(name, e.Button, Control.MousePosition);
            if (netWork != null)
            {
                Point p = Control.MousePosition;
                Point tm = role.Equals("1") ? Common.reduce(p) : Common.amplify(p);
                WBMsgUiMove_MouseMove msgUiMove_MouseMove = new WBMsgUiMove_MouseMove();
                msgUiMove_MouseMove.name = name;
                msgUiMove_MouseMove.button = e.Button;
                msgUiMove_MouseMove.mousePos = tm;
                netWork.SendWBMsgConnectedHdlr(msgUiMove_MouseMove);
            }
        }
        public void whenUiMove_MouseMove(String name, MouseButtons button, Point mousePos)
        {
            if (button == MouseButtons.Left && bDragging)
            {
                mousePos.Offset(mouse_offset.X, mouse_offset.Y);//设置偏移
                Control control = GetControl(name, this.Drawing);
                if (control == null) return;
                control.Location = control.Parent.PointToClient(mousePos);
            }
        }
        //根据名字得到控件
        private Control GetControl(string name, Control parent)
        {
            foreach (Control Item in parent.Controls)
            {
                if (Item.Name == name)
                {
                    return Item;
                }
                else
                {
                    Control control = GetControl(name, Item);
                    if (control != null)
                    {
                        return control;
                    }
                }
            }
            return null;
        }
        private void UiMove_MouseUp(object sender, MouseEventArgs e)
        {
            whenUiMove_MouseUp();
            if (netWork != null)
            {
                WBMsgUiMove_MouseUp msgUiMove_MouseUp = new WBMsgUiMove_MouseUp();
                netWork.SendWBMsgConnectedHdlr(msgUiMove_MouseUp);
            }
        }
        public void whenUiMove_MouseUp()
        {
            bDragging = false;
        }
        ////////////////////////////////////////////////////////网络传输通讯////////////////////
        public NetworkManager netWork;
        //侦查上传图片
        public void whenUploadImage(byte[] byteArrayIn, String name)
        {
            if (!byteArrayIn.Length.Equals(0))
            {
                string path = Application.StartupPath;
                path += "\\pic\\" + name;
                MemoryStream MS = new MemoryStream(byteArrayIn);
                Bitmap image = new System.Drawing.Bitmap(MS);
                image.Save(path);
                this.frmMenu.changeBtn("btZC", "1");
            }
        }
        //全息信息上传
        public void whenAlldirective(byte[] byteArrayIn, String name)
        {
            if (!byteArrayIn.Length.Equals(0))
            {
                string path = Application.StartupPath;
                path += "\\alldirective\\" + name;
                MemoryStream MS = new MemoryStream(byteArrayIn);
                Bitmap image = new System.Drawing.Bitmap(MS);
                image.Save(path);
            }
        }
        /// <summary>
        /// 设置soket的连接状态
        /// </summary>
        /// <param name="StrText"></param>
        /// <param name="StrWaveFileName"></param>
        public void SetMusicalStatus(String type, string state)
        {

            if (this.netWork != null)
            {
                if (type.Equals("stop"))
                {
                    switch (netWork.soketType)
                    {
                        case SOKET_TYPE.enClientMode:
                            //如果为客户端模式，更改客户端的连接状态
                            this.clientState.Text = "未连接服务器";
                            this.netWork = null;
                            break;

                    }
                }
                else
                {
                    switch (netWork.soketType)
                    {
                        case SOKET_TYPE.enClientMode:
                            //如果为客户端模式，更改客户端的连接状态
                            this.clientState.Text = "连接到服务器";
                            break;
                    }
                }
            }
        }
        //画图时对应的发送信息
        public void WhenMouseSentToPeers(String type, Point p)
        {
            if (netWork != null)
            {

                Point tm = role.Equals("1") ? Common.reduce(p) : Common.amplify(p);
                switch (type)
                {
                    case "down":
                        WBMsgDrawMouseDown Msgbegin = new WBMsgDrawMouseDown();
                        Msgbegin.startPoint = tm;
                        netWork.SendWBMsgConnectedHdlr(Msgbegin);
                        break;
                    case "move":
                        WBMsgDrawMouseMove MsgLine = new WBMsgDrawMouseMove();
                        MsgLine.movPoint = tm;
                        netWork.SendWBMsgConnectedHdlr(MsgLine);
                        break;
                    case "up":
                        WBMsgDrawMouseUp Msgend = new WBMsgDrawMouseUp();
                        Msgend.endPoint = tm;
                        netWork.SendWBMsgConnectedHdlr(Msgend);
                        break;
                    default:
                        break;
                }
            }
        }
        //启动
        private void startNetwork()
        {
            if (netWork == null)
            {
                netWork = new NetworkManager(ConfigurationManager.AppSettings["whiteboard_serverIP"], ConfigurationManager.AppSettings["whiteboard_serverPort"], SOKET_TYPE.enServerMode);
                netWork.frm_Main = this;
                netWork.StartListening();
                stop_soket.Enabled = true;
            }
        }  
        //关闭服务器
        private void stopNetwork()
        {
            if (netWork != null){
               
                netWork.Disconnect();
                netWork = null;
                stop_soket.Enabled = false;
            }
        }
        //连接
        private void connectNetwork(){
            string ip = ConfigurationManager.AppSettings["whiteboard_serverIP"];
            string port = ConfigurationManager.AppSettings["whiteboard_serverPort"];
            if (netWork == null)
            {
                netWork = new NetworkManager(ip, port, SOKET_TYPE.enClientMode);
                netWork.frm_Main = this;
                Boolean isconnect = netWork.ConnectToListeningServer();
                if (isconnect)
                { //连接成功
                    this.clientState.Text = "连接成功";
                }
                else
                {
                    netWork = null;
                    this.clientState.Text = "正在连接...";
                }
            }
            else
            {//不为空是，判断服务器是否关闭

                try
                {//当服务器断开socket.Connected将抛出异常 
                    if (netWork.clientHandler.socket.Connected)
                    {
                       
                    }
                }
                catch (Exception e){
                    netWork = null;
                    this.clientState.Text = "正在连接...";
                    //  MessageBox.Show(e.Message);
                }
            }

        }
        //定时连接服务器，
        private void networkTimer_Tick(object sender, EventArgs e){
            connectNetwork();
        }
        //清除
        private void clearScreen(object sender, EventArgs e)
        {
            this.clearScreen();
            if (netWork != null)
            {
                WBMsgClearScreen screen = new WBMsgClearScreen();
                netWork.SendWBMsgConnectedHdlr(screen);
            }
        }

        private void stopSoket(object sender, EventArgs e)
        {
            if (netWork != null)
            {
                netWork.Disconnect();
            }
        }

        #endregion


        #region 肖军
        private void FormInit()
        {
            dbConnect = new SqlConnection();
            dbConnect = SqlConnection();

            dbThreadConnect = new SqlConnection();
            dbThreadConnect = SqlConnection();

            this.timerInfo.Interval = 50;
        }

        /// <summary>
        /// 根据本机IP取人员姓名
        /// </summary>
        /// <param name="localIP"></param>
        /// <returns></returns>
        private string getNameByIP(string localIP)
        {
            string uname = "";
            string sql1 = "select UserName from UserInfo where ipaddr='" + localIP + "'";
            SqlDataReader reader1 = null;
            SqlCommand cmd1 = new SqlCommand(sql1, dbConnect);
            reader1 = cmd1.ExecuteReader();

            while (reader1.Read())
            {
                uname = reader1["UserName"].ToString();                
            }
            reader1.Close();
            return uname;
        }
        //
        public bool InfoConnectServer()
        {
            string ip = ConfigurationManager.AppSettings["whiteboard_serverIP"];
            string port = ConfigurationManager.AppSettings["order_serverPort"];
            LocalIP = ConfigurationManager.AppSettings["Self_IP"];
            //连接
            MyName = getNameByIP(LocalIP);   //获取本机人员名称
            if (MyName == "")   //没取到人名，配置数据库人员表数据
            {
                MessageBox.Show("后台数据库中，没有与当前IP对应的用户信息，请与管理员联系！");
                this.Close();
            }
            socket = new AsySocket(LocalIP, 0);//LocalIP
            socket.OnSended += new AsySocketEventHandler(socket_OnSended);
            socket.OnSendTo += new AsySocketEventHandler(socket_OnSendTo);
            socket.OnStringDataAccept += new StringDataAcceptHandler(socket_OnStringDataAccept);
            socket.OnClosed += new AsySocketClosedEventHandler(socket_OnClosed);
            try
            {
                socket.LinkObject.Connect(ip, Int32.Parse(port));
            }
            catch
            {
                if (socket != null)
                    socket = null;
                //if (this.timerInfo.Enabled==false)
                //    this.timerInfo.Start();
                //throw new Exception("未能连接上指挥中心，请等待！");
                return false;
            }
            socket.BeginAcceptData();
            this.timerInfo.Stop();
            return true;
        }

        //连接数据库
        public static SqlConnection SqlConnection()
        {
            try
            {
                SqlConnection sqlConn = null;
                sqlConn = new SqlConnection(SQLCONNSTR);
                sqlConn.Open();
                return sqlConn;
            }
            catch
            {
                throw new Exception("SQL Connection Error!");
            }
        }

        DateTime beginTime;
        public void StartorEnd(string flag)
        {
            this.label1.Visible = true;
            if (flag == "1")
            {
                //label1.Text = "正在救援……计时：" + "";
                this.beginTime = DateTime.Now;
                this.timerInfo.Start();
            }
            else
            {
                this.timerInfo.Stop();
                this.label1.Text = "结束救援……";
            }
        }

        private void timerInfo_Tick(object sender, EventArgs e)
        {
            TimeSpan ts = DateTime.Now - this.beginTime; // 使用当前时间减去启动时记录的时间
            this.label1.Text = "正在救援……计时：" + ts.Hours.ToString("d2") + ":" + ts.Minutes.ToString("d2") + ":" + ts.Seconds.ToString("d2");// +"." + ts.Milliseconds.ToString("d2");
                    
        }

        #region 消息指令操作
        void socket_OnStringDataAccept(string AccepterID, string AcceptData)
        {
            AddMsg(AcceptData);

        }

        void socket_OnClosed(string SocketID, string ErrorMessage)
        {
            InfoConnectServer();
        }

        void socket_OnSendTo(string SenderID, string EventMessage)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        void socket_OnSended(string SenderID, string EventMessage)
        {
            string sendtime = DateTime.Now.ToLongTimeString().ToString();
        }

        private void AddMsg(string msg)
        {
            //判断是图标指令还是文字指令
            int a = msg.IndexOf("pictureBox");//a会等于1
            if (a > 0)
            {
                if ((msg.Split('：'))[1].Substring(0, 10) == "pictureBox")
                {
                    if (frmMsg.picmsg == "")
                        frmMsg.picmsg = msg.Substring(0, msg.Length - 1);
                    else
                        frmMsg.picmsg = frmMsg.picmsg + ";" + msg.Substring(0, msg.Length - 2); // Environment.NewLine 
                }
            }
            else
            {

                if (frmMsg.msg == "")
                    frmMsg.msg = msg.Substring(0, msg.Length - 1);
                else
                    frmMsg.msg = msg.Substring(0, msg.Length - 2) + Environment.NewLine + frmMsg.msg;
            }
            if (frmMsg.Visible) //若子窗体显示
            {
                frmMsg.Hide();
                frmMsg.Show();
                frmMsg.Refresh();
                frmMenu.changeBtn("btnJSXX", "0");
            }
            else
            {
                frmMenu.changeBtn("btnJSXX", "1");
            }
        }

        private void AddMsgCallBack(string msg)
        {
            if (frmMsg.msg == "")
                frmMsg.msg = msg.Substring(0, msg.Length - 1);
            else
                frmMsg.msg = msg.Substring(0, msg.Length - 1) + Environment.NewLine + frmMsg.msg;

            if (frmMsg.Visible) //若子窗体显示
            {
                frmMsg.Hide();
                frmMsg.Show();
                frmMsg.Refresh();
                frmMenu.changeBtn("btnJSXX", "0");
            }
            else
            {
                frmMenu.changeBtn("btnJSXX", "1");
            }
        }
        #endregion

       
        #endregion
        #region 冯曦
        /// <summary>
        /// 语音监听服务的IP地址
        /// </summary>
        public static string Audio_serverIP = System.Configuration.ConfigurationManager.AppSettings["Self_IP"];
        public static string ServicesCenterIP = System.Configuration.ConfigurationManager.AppSettings["whiteboard_serverIP"];
        /// <summary>
        /// 语音监听服务的端口号
        /// </summary>
        public static string Audio_serverPort = System.Configuration.ConfigurationManager.AppSettings["Audio_serverPort"];
        /// <summary>
        /// 关于语音的服务SCOKET
        /// </summary>
        public NetworkManager aduio_netWork;
        /// <summary>
        /// 关于语音的客户SCOKET
        /// </summary>
        public NetworkManager aduio_client_netWork;
        public UdpServer m_pUdpServer = null;
        public IPEndPoint m_pTargetEP = null;
        public WaveIn m_pWaveIn = null;
        public WaveOut m_pWaveOut = null;

        public static string Udp_AudioPort = System.Configuration.ConfigurationManager.AppSettings["Udp_AudioPort"];
        public static int m_Codec = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["G711_a_law"]);
        public static int WavInDevice_idx = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WavInDevice"]);
        public static int WavOutDevice_idx = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WavOutDevice"]);

        public bool m_IsRunning = false;
        public bool m_IsSendingMic = false;
        public string UseringIP = String.Empty;
        Thread tmpThread = null;
        /// <summary>
        /// 呼叫端的IP
        /// </summary>
        public string CallerIP = String.Empty;


        private void InitUdpCall()
        {
            if (m_pUdpServer != null)
            {
                m_pUdpServer.Dispose();
                m_pUdpServer = null;
            }

            if (m_pWaveOut != null)
            {
                m_pWaveOut.Dispose();
                m_pWaveOut = null;
            }

            m_IsRunning = true;

            //选用设备中的第一种设备做为驱动
            m_pWaveOut = new WaveOut(WaveOut.Devices[WavOutDevice_idx], 8000, 16, 1);

            m_pUdpServer = new UdpServer();
            m_pUdpServer.Bindings = new IPEndPoint[] { new IPEndPoint(IPAddress.Parse(Form1.Audio_serverIP), Convert.ToInt32(Udp_AudioPort)) };
            m_pUdpServer.PacketReceived += new PacketReceivedHandler(m_pUdpServer_PacketReceived);
            m_pUdpServer.Start();
        }

        /// <summary>
        /// 这个方法是我们得到UDP传来的声音后，进行声音播放
        /// </summary>
        /// <param name="e">Event data.</param>
        public void m_pUdpServer_PacketReceived(UdpPacket_eArgs e)
        {
            // Decompress data.
            byte[] decodedData = null;
            if (m_Codec == 0)
            {
                decodedData = G711.Decode_aLaw(e.Data, 0, e.Data.Length);
            }
            else if (m_Codec == 1)
            {
                decodedData = G711.Decode_uLaw(e.Data, 0, e.Data.Length);
            }

            // We just play received packet.
            m_pWaveOut.Play(decodedData, 0, decodedData.Length);

        }

        /// <summary>
        /// 当录音缓冲区满时，我们需要传递出去
        /// </summary>
        /// <param name="buffer">Recorded data.</param>
        public void m_pWaveIn_BufferFull(byte[] buffer)
        {
            // Compress data. 
            byte[] encodedData = null;
            if (m_Codec == 0)
            {
                encodedData = G711.Encode_aLaw(buffer, 0, buffer.Length);
            }
            else if (m_Codec == 1)
            {
                encodedData = G711.Encode_uLaw(buffer, 0, buffer.Length);
            }

            // We just sent buffer to target end point.
            m_pUdpServer.SendPacket(encodedData, 0, encodedData.Length, m_pTargetEP);
        }

        /// <summary>
        /// 关闭声音录入
        /// </summary>
        public void CloseWaveIn()
        {
            m_IsSendingMic = false;
            if (m_pWaveIn != null)
            {
                m_pWaveIn.Dispose();
                m_pWaveIn = null;
            }
        }

        public void OpenVaveIn()
        {
            m_IsSendingMic = true;

            m_pWaveIn = new WaveIn(WaveIn.Devices[Form1.WavInDevice_idx], 8000, 16, 1, 400);
            m_pWaveIn.BufferFull += new BufferFullHandler(m_pWaveIn_BufferFull);
            m_pWaveIn.Start();
        }



        ///// <summary>
        ///// InitAudio
        ///// </summary>
        private void InitAudio()
        {
            try
            {
                CreateHandle();
                //if (aduio_netWork == null)
                //{
                //    aduio_netWork = new NetworkManager(Audio_serverIP, Audio_serverPort, SOKET_TYPE.enServerMode);

                //}
                //aduio_netWork.frm_Main = this;
                //aduio_netWork.StartListening();
                #region 初始化数据库中自身对应IP的处理状态为未处理状态
                string sql1 = "update UserInfo set IsBroadcastingHandle=0,IsUdpCallHandle=0 where ipaddr = '" + Audio_serverIP + "'";
                SqlCommand cmd1 = new SqlCommand(sql1, dbConnect);
                cmd1.ExecuteNonQuery();
                #endregion

                #region 启动线程来监视各个IP的状态变化
                tmpThread = new Thread(new ThreadStart(MonitoringControl));
                tmpThread.Name = "MainThread";
                tmpThread.Start();
                #endregion
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// 线程处理，这里主要处理广播和点播在客户端的各种连接状态
        /// </summary>
        private void MonitoringControl()
        {
            while (true)
            {
                SqlCommand cmd1 = null;
                SqlDataAdapter adapter = null;
                //得到数据库中的语音部分的记录
                string sql = "select ipaddr,isLeader,isHasPad,IsBroadcasting,IsCall,callIp,IsBroadcastingHandle,IsUdpCallHandle from UserInfo where rfid='0000' or isHasPad=1 ";
                
                cmd1 = new SqlCommand(sql, dbThreadConnect);
                DataTable dt = new DataTable();
                adapter = new SqlDataAdapter(cmd1);
                adapter.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                    //得到服务端的状态记录
                    DataRow[] dr = dt.Select("ipaddr = '" + Audio_serverIP + "'");
                    if (dr.Length > 0)
                    {
                        //如果没有广播，那么就处理单点通讯事件
                        if (dr[0]["IsBroadcasting"].ToString() != "1")
                        {
                            RichterShowState();
                            //如果语音没有处理，那么需要进行处理
                            if (dr[0]["IsUdpCallHandle"].ToString() != "1")
                            {
                                switch (dr[0]["IsCall"].ToString())
                                {
                                    //如果是被动呼叫连通了，那么需要更改状态
                                    case "201":
                                        //首先被呼叫端与呼叫端进行UDP连接
                                        try
                                        {
                                            CallerIP = dr[0]["callIp"].ToString();
                                            m_pTargetEP = new IPEndPoint(IPAddress.Parse(CallerIP), Convert.ToInt32(Form1.Udp_AudioPort));
                                            OpenVaveIn();
                                            ControlEnd(Audio_serverIP, 0);
                                        }
                                        catch
                                        {
                                            MessageBox.Show(this, "Invalid target IP address or port !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            return;
                                        }
                                        break;
                                    //如果是被动呼叫连通等待中，那么要增加按钮的闪动进行提示
                                    case "202":

                                        break;
                                    //如果是被动呼叫中断，那么需要关闭声音，同时去断开呼叫端
                                    case "203":
                                        //关闭语音通道
                                        CloseWaveIn();
                                        if (m_pTargetEP != null)
                                            m_pTargetEP = null;
                                        ControlEnd(Audio_serverIP, 0);
                                        break;
                                    //如果主动端连通，那么需要更改状态
                                    case "101":
                                        try
                                        {
                                            CallerIP = dr[0]["callIp"].ToString();
                                            m_pTargetEP = new IPEndPoint(IPAddress.Parse(CallerIP), Convert.ToInt32(Form1.Udp_AudioPort));
                                            OpenVaveIn();
                                            ControlEnd(Audio_serverIP, 0);
                                        }
                                        catch
                                        {
                                            MessageBox.Show(this, "Invalid target IP address or port !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            return;
                                        }
                                        ControlEnd(Audio_serverIP, 0);
                                        break;
                                    //如果主动端呼叫等待中
                                    case "102":
                                        break;
                                    //如果主动呼叫端中断
                                    case "103":
                                        //关闭语音通道
                                        CloseWaveIn();
                                        if (m_pTargetEP != null)
                                            m_pTargetEP = null;
                                        ControlEnd(Audio_serverIP, 0);
                                        break;
                                }

                            }
                            if (dr[0]["IsUdpCallHandle"].ToString() == "1")
                            {
                                switch (dr[0]["IsCall"].ToString())
                                {
                                    case "103":
                                    case "203":
                                        ControlEnd(Audio_serverIP, 2);
                                        break;
                                }
                            }
                        }
                        else //这里表示是广播开始
                        {
                            RichterShowState();
                            switch (dr[0]["IsBroadcastingHandle"].ToString())
                            {
                                //如果没有开启广播服务，那么需要开启
                                case "0":
                                    //判断是否连接上广播，如果连接成功，则修改状态字为连接
                                    if (ClientStart())
                                    {
                                        //检查要广播的对象是否正在通话,如果正在通话，那么就先关闭UDP声音
                                        DataRow[] drNew = dt.Select("ipaddr = '" + Audio_serverIP + "'");
                                        if (drNew[0]["IsUdpCallHandle"].ToString() == "1" && (drNew[0]["IsCall"].ToString() == "101" ||
                                            drNew[0]["IsCall"].ToString() == "201"))
                                        {
                                            CloseWaveIn();
                                            if (m_pTargetEP != null)
                                                m_pTargetEP = null;
                                        }
                                        //将广播状态设置为正在进行中
                                        ControlEnd(Audio_serverIP, 1);
                                    }                                    
                                    break;
                                case "1":
                                    DataRow[] drNew1 = dt.Select("ipaddr = '" + Audio_serverIP + "'");
                                    if (drNew1[0]["IsUdpCallHandle"].ToString() == "0" && (drNew1[0]["IsCall"].ToString() == "103" ||
                                        drNew1[0]["IsCall"].ToString() == "203"))
                                    {
                                        CloseWaveIn();
                                        if (m_pTargetEP != null)
                                            m_pTargetEP = null;
                                    }
                                    ControlEnd(Audio_serverIP, 2);
                                    break;
                                //如果广播服务还在启动，那么需要关闭
                                case "2":
                                    //首先，需要将暂停的事务重新开启
                                    if (dr[0]["IsUdpCallHandle"].ToString() == "1" && (dr[0]["IsCall"].ToString() == "101" ||
                                        dr[0]["IsCall"].ToString() == "201"))
                                    {
                                        m_pTargetEP = new IPEndPoint(IPAddress.Parse(dr[0]["callIp"].ToString()), Convert.ToInt32(Form1.Udp_AudioPort));
                                        OpenVaveIn();
                                    }
                                    ControlEnd(Audio_serverIP, 4);
                                    break;
                            }
                        }
                    }
                }
                
                cmd1.Dispose();
                cmd1 = null;
                adapter.Dispose();
                adapter = null;
                Thread.Sleep(1000);
            }
        }

        /// <summary>
        /// 界面闪动控制
        /// </summary>
        private void RichterShowState()
        {
            string sql = string.Empty;
            SqlCommand sqlCommand = null;
            SqlDataAdapter adapter = null;
            DataTable dt = null;

            //首先取出所有的数据
            sql = " select ipaddr,rfid,isLeader,isHasPad,IsBroadcasting,IsCall,callIp,IsBroadcastingHandle,IsUdpCallHandle from [ShanDongFire].[dbo].userinfo where rfid='0000' or isHasPad=1 ";
            sqlCommand = new SqlCommand(sql, dbThreadConnect);
            dt = new DataTable();
            adapter = new SqlDataAdapter(sqlCommand);
            adapter.Fill(dt);

            //处理主窗口的语音菜单的闪动信息
            DataRow[] dr = dt.Select("ipaddr = '" + Audio_serverIP + "'");
            if (frmMenu != null)
            {
                if (dr[0]["IsBroadcasting"].ToString() == "1" || dr[0]["IsCall"].ToString() != "0")
                {
                    frmMenu.SoundFlickerStart();
                }
                else
                {
                    frmMenu.SoundFlickerStop();
                }
            }
            string callIp = dr[0]["callIp"].ToString();
            string serverIp = GetConfigurationValue("whiteboard_serverIP");

            //处理语音窗口的信息闪动
            if (frmSound != null)
            {
                //如果是广播状态
                if (dr[0]["IsBroadcasting"].ToString() == "1")
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["IsBroadcastingHandle"].ToString() == "1" && dt.Rows[i]["ipaddr"].ToString() != dr[0]["ipaddr"].ToString())
                        {
                            frmSound.SoundFickerYellow(dt.Rows[i]["ipaddr"].ToString(),1);
                        }
                        else
                        {
                            frmSound.SoundFickerToGreen(dt.Rows[i]["ipaddr"].ToString(), 1);
                        }
                    }

                    if (dr[0]["IsBroadcastingHandle"].ToString() == "1")
                    {
                        frmSound.SoundFickerYellow(Audio_serverIP,1);
                        frmSound.HideOtherCallBtn(Audio_serverIP);
                    }
                    else
                    {
                        frmSound.SoundFickerToGreen(Audio_serverIP,1);
                        frmSound.ShowOtherCallBtn();
                    }
                }
                else
                {
                    //如果是点对点通讯，那么需要先设置状态
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["IsBroadcastingHandle"].ToString() == "1" && dt.Rows[i]["IsBroadcasting"].ToString() == "1")
                        {
                            frmSound.SoundFickerToRed(dt.Rows[i]["ipaddr"].ToString(), 0);
                            continue;
                        }

                        switch (dt.Rows[i]["IsCall"].ToString())
                        {
                            case "102":
                            case "202":
                            case "101":
                            case "201":
                                if (dt.Rows[i]["rfid"].ToString() == "0000")
                                {
                                    //让指挥中心闪动
                                    frmSound.SoundFickerToRed("", 1);
                                }
                                else
                                {
                                    frmSound.SoundFickerToRed(dt.Rows[i]["ipaddr"].ToString(),0);
                                }
                                //if (dt.Rows[i]["ipaddr"].ToString() != callIp)
                                //{
                                //    frmSound.HideSingleCallBtn(dt.Rows[i]["ipaddr"].ToString());
                                //}                               
                                break;
                            case "103":
                            case "203":
                            case "0":
                                if (dt.Rows[i]["rfid"].ToString() == "0000")
                                {
                                    frmSound.SoundFickerToGreen("", 1);
                                }
                                else
                                {
                                    frmSound.SoundFickerToGreen(dt.Rows[i]["ipaddr"].ToString(), 0);
                                }
                                //if (dt.Rows[i]["ipaddr"].ToString() != callIp)
                                //{
                                //    frmSound.ShowSingleCallBtn(dt.Rows[i]["ipaddr"].ToString());
                                //}
                                break;
                        }
                    }

                    //现在根据对应的IP来设置状态
                    switch (dr[0]["IsCall"].ToString())
                    {
                        case "101":
                            if (dr[0]["IsUdpCallHandle"].ToString() == "1")
                            {
                                if (dr[0]["callIp"].ToString() == serverIp)
                                {
                                    frmSound.SoundFickerYellow("", 1);
                                }
                                else
                                {
                                    frmSound.SoundFickerYellow(callIp, 0);
                                }
                            }
                            break;
                        case "102":
                            if (dr[0]["callIp"].ToString() == serverIp)
                            {
                                frmSound.SoundFlickerStart("", 1);
                            }
                            else
                            {
                                frmSound.SoundFlickerStart(callIp, 0);
                            }
                            break;
                        case "201":
                            if (dr[0]["IsUdpCallHandle"].ToString() == "1")
                            {
                                if (dr[0]["callIp"].ToString() == serverIp)
                                {
                                    frmSound.SoundFickerYellow("",1);
                                }
                                else
                                {
                                    frmSound.SoundFickerYellow(callIp, 0);
                                }
                            }
                            break;
                        case "202":
                            if (dr[0]["callIp"].ToString() == serverIp)
                            {
                                frmSound.SoundFlickerStart("", 1);
                            }
                            else
                            {
                                frmSound.SoundFlickerStart(callIp, 0);
                            }
                            frmSound.HideOtherCallBtn(callIp);
                            break;
                        case "203":
                        case "103":
                            if (dr[0]["callIp"].ToString() == serverIp)
                            {
                                frmSound.SoundFickerGreen("", 1);
                            }
                            else
                            {
                                frmSound.SoundFickerGreen(callIp, 0);
                            }
                            frmSound.ShowOtherCallBtn();
                            break;
                    }
                }
            }

            adapter.Dispose();
            adapter = null;
            sqlCommand.Dispose();
            sqlCommand = null;
        }

        private void ControlEnd(string ip, int controlType)
        {
            string sql = string.Empty;
            SqlCommand sqlCommand = null;
            switch (controlType)
            {
                case 0:
                    sql = "update UserInfo set IsUdpCallHandle = 1 where ipaddr = '" + ip + "'";
                    sqlCommand = new SqlCommand(sql, dbThreadConnect);
                    sqlCommand.ExecuteNonQuery();
                    break;
                case 1:
                    sql = "update UserInfo set IsBroadcastingHandle = 1 where ipaddr = '" + ip + "'";
                    sqlCommand = new SqlCommand(sql, dbThreadConnect);
                    sqlCommand.ExecuteNonQuery();
                    break;
                case 2:
                    sql = "update UserInfo set IsUdpCallHandle = 0,callIp='',IsCall=0 where ipaddr = '" + ip + "'";
                    sqlCommand = new SqlCommand(sql, dbThreadConnect);
                    sqlCommand.ExecuteNonQuery();
                    break;
                case 4:
                    sql = "update UserInfo set IsBroadcastingHandle = 0,IsBroadcasting=0 where ipaddr = '" + ip + "'";
                    sqlCommand = new SqlCommand(sql, dbThreadConnect);
                    sqlCommand.ExecuteNonQuery();
                    break;
            }
            sqlCommand.Dispose();
            sqlCommand = null;
        }

        #region 广播
        #region 语音使用字段
        //Attribute
        private NF.TCPClient m_Client;
        private NF.TCPServer m_Server;
        private Configuration m_Config = new Configuration();
        private String m_ConfigFileName = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "config.xml");
        private int m_SoundBufferCount = 8;
        private WinSound.Protocol m_PrototolClient = new WinSound.Protocol(WinSound.ProtocolTypes.LH, Encoding.Default);
        private Dictionary<NF.ServerThread, ServerThreadData> m_DictionaryServerDatas = new Dictionary<NF.ServerThread, ServerThreadData>();
        private WinSound.Recorder m_Recorder_Client;
        private WinSound.Recorder m_Recorder_Server;
        private WinSound.Player m_PlayerClient;
        private uint m_RecorderFactor = 4;
        private WinSound.JitterBuffer m_JitterBufferClientRecording;
        private WinSound.JitterBuffer m_JitterBufferClientPlaying;
        private WinSound.JitterBuffer m_JitterBufferServerRecording;
        WinSound.WaveFileHeader m_FileHeader = new WinSound.WaveFileHeader();
        private bool m_IsFormMain = true;
        private long m_SequenceNumber = 4596;
        private long m_TimeStamp = 0;
        private int m_Version = 2;
        private bool m_Padding = false;
        private bool m_Extension = false;
        private int m_CSRCCount = 0;
        private bool m_Marker = false;
        private int m_PayloadType = 0;
        private uint m_SourceId = 0;
        private System.Windows.Forms.Timer m_TimerProgressBarFile = new System.Windows.Forms.Timer();
        private System.Windows.Forms.Timer m_TimerProgressBarPlayingClient = new System.Windows.Forms.Timer();
        private WinSound.EventTimer m_TimerStream = new WinSound.EventTimer();
        private Byte[] m_FilePayloadBuffer;
        private int m_RTPPartsLength = 0;
        private uint m_Milliseconds = 20;

        private Object LockerDictionary = new Object();
        //是否初始化广播
        private bool IsInitBroadcasting = false;
        //是否初始化点对点语音
        private bool IsInitCall = false;
        #endregion
        #region 属性
        /// <summary>
        ///IsServerRunning 
        /// </summary>
        private bool IsServerRunning
        {
            get
            {
                if (m_Server != null)
                {
                    return m_Server.State == NF.TCPServer.ListenerState.Started;
                }
                return false;
            }
        }
        /// <summary>
        /// IsClientConnected
        /// </summary>
        private bool IsClientConnected
        {
            get
            {
                if (m_Client != null)
                {
                    return m_Client.Connected;
                }
                return false;
            }
        }
        /// <summary>
        /// IsPlayingToSoundDeviceWanted
        /// </summary>
        private bool IsPlayingToSoundDeviceWanted
        {
            get
            {
                //if (ComboboxOutputSoundDeviceNameClient.SelectedIndex >= 1)
                if (true)
                {
                    return true;
                }
                return false;
            }
        }
        /// <summary>
        /// IsRecorderStarted
        /// </summary>
        private bool IsRecorderFromSounddeviceStarted_Client
        {
            get
            {
                if (m_Recorder_Client != null)
                {
                    return m_Recorder_Client.Started;
                }
                return false;
            }
        }
        /// <summary>
        /// IsRecorderFromSounddeviceStarted_Server
        /// </summary>
        private bool IsRecorderFromSounddeviceStarted_Server
        {
            get
            {
                if (m_Recorder_Server != null)
                {
                    return m_Recorder_Server.Started;
                }
                return false;
            }
        }

        /// <summary>
        /// UseJitterBuffer
        /// </summary>
        private bool UseJitterBufferServer
        {
            get
            {
                return m_Config.JitterBufferCountServer >= 2;
            }
        }
        /// <summary>
        /// UseJitterBuffer
        /// </summary>
        private bool UseJitterBufferClientRecording
        {
            get
            {
                return m_Config.UseJitterBufferClientRecording;
            }
        }
        /// <summary>
        /// UseJitterBufferServerRecording
        /// </summary>
        private bool UseJitterBufferServerRecording
        {
            get
            {
                return m_Config.UseJitterBufferServerRecording;
            }
        }
        #endregion
        #region 方法
        /// <summary>
        /// 得到配置文件的APPSETTINGS节点的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private string GetConfigurationValue(string key)
        {
            return System.Configuration.ConfigurationManager.AppSettings[key];
        }
        /// <summary>
        /// Init
        /// </summary>
        private void Init()
        {
            try
            {                
                //InitComboboxes();
                LoadConfig();
                InitJitterBufferClientRecording();
                InitJitterBufferClientPlaying();
                InitJitterBufferServerRecording();
                InitProtocolClient();
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// InitProtocolClient
        /// </summary>
        private void InitProtocolClient()
        {
            if (m_PrototolClient != null)
            {
                m_PrototolClient.DataComplete += new WinSound.Protocol.DelegateDataComplete(OnProtocolClient_DataComplete);
            }
        }

        /// <summary>
        /// OnProtocolClient_DataComplete
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        private void OnProtocolClient_DataComplete(Object sender, Byte[] data)
        {
            try
            {
                //Wenn der Player gestartet wurde
                if (m_PlayerClient != null)
                {
                    if (m_PlayerClient.Opened)
                    {
                        //RTP Header auslesen
                        WinSound.RTPPacket rtp = new WinSound.RTPPacket(data);

                        //Wenn Header korrekt
                        if (rtp.Data != null)
                        {
                            //In JitterBuffer hinzufügen
                            if (m_JitterBufferClientPlaying != null)
                            {
                                m_JitterBufferClientPlaying.AddData(rtp);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// 配置音频聊天的基本参数
        /// </summary>
        private void LoadConfig()
        {
            List<String> playbackNames = WinSound.WinSound.GetPlaybackNames();
            List<String> recordingNames = WinSound.WinSound.GetRecordingNames();

            //Output
            foreach (String name in playbackNames.Where(x => x != null))
            {
                m_Config.SoundOutputDeviceNameClient = name;
                m_Config.SoundOutputDeviceNameServer = name;

            }
            //Input
            foreach (String name in recordingNames.Where(x => x != null))
            {
                m_Config.SoundInputDeviceNameServer = name;
                m_Config.SoundInputDeviceNameClient = name;
            }

            m_Config.IpAddressClient = GetConfigurationValue("whiteboard_serverIP");
            m_Config.IPAddressServer = GetConfigurationValue("whiteboard_serverIP");
            m_Config.PortClient = Convert.ToInt32(GetConfigurationValue("Client_AudioPort"));
            m_Config.PortServer = Convert.ToInt32(GetConfigurationValue("Server_AudioPort"));
            m_Config.SamplesPerSecondClient = Convert.ToInt32(GetConfigurationValue("Client_SamplesPer"));
            m_Config.JitterBufferCountServer = Convert.ToUInt32(GetConfigurationValue("Server_Jitter"));
            m_Config.JitterBufferCountClient = Convert.ToUInt32(GetConfigurationValue("Client_Jitter"));
            m_Config.SamplesPerSecondServer = Convert.ToInt32(GetConfigurationValue("Server_SamplesPer"));
            m_Config.BitsPerSampleServer = 16;
            m_Config.BitsPerSampleClient = 16;
            m_Config.ChannelsServer = 2;
            m_Config.ChannelsClient = 2;
            m_Config.UseJitterBufferClientRecording = true;
            m_Config.UseJitterBufferServerRecording = true;
            //ConfigToForm();
        }

        /// <summary>
        /// InitJitterBufferClientRecording
        /// </summary>
        private void InitJitterBufferClientRecording()
        {
            //Wenn vorhanden
            if (m_JitterBufferClientRecording != null)
            {
                m_JitterBufferClientRecording.DataAvailable -= new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferClientDataAvailableRecording);
            }

            //Neu erstellen
            m_JitterBufferClientRecording = new WinSound.JitterBuffer(null, 20, 20);
            m_JitterBufferClientRecording.DataAvailable += new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferClientDataAvailableRecording);
        }


        /// <summary>
        /// OnJitterBufferClientDataAvailable
        /// </summary>
        /// <param name="rtp"></param>
        private void OnJitterBufferClientDataAvailableRecording(Object sender, WinSound.RTPPacket rtp)
        {
            try
            {
                if (IsClientConnected)
                {
                    if (m_IsFormMain)
                    {
                        //RTP Packet in Bytes umwandeln
                        Byte[] rtpBytes = rtp.ToBytes();
                        //Absenden
                        m_Client.Send(m_PrototolClient.ToBytes(rtpBytes));
                    }
                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }


        /// <summary>
        /// InitJitterBufferClientPlaying
        /// </summary>
        private void InitJitterBufferClientPlaying()
        {
            //Wenn vorhanden
            if (m_JitterBufferClientPlaying != null)
            {
                m_JitterBufferClientPlaying.DataAvailable -= new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferClientDataAvailablePlaying);
            }

            //Neu erstellen
            m_JitterBufferClientPlaying = new WinSound.JitterBuffer(null, m_Config.JitterBufferCountClient, 20);
            m_JitterBufferClientPlaying.DataAvailable += new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferClientDataAvailablePlaying);
        }

        /// <summary>
        /// OnJitterBufferClientDataAvailablePlaying
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="rtp"></param>
        private void OnJitterBufferClientDataAvailablePlaying(Object sender, WinSound.RTPPacket rtp)
        {
            try
            {
                if (m_PlayerClient != null)
                {
                    if (m_PlayerClient.Opened)
                    {
                        if (m_IsFormMain)
                        {
                            //Wenn nicht stumm
                            if (m_Config.MuteClientPlaying == false)
                            {
                                //Nach Linear umwandeln
                                Byte[] linearBytes = WinSound.Utils.MuLawToLinear(rtp.Data, m_Config.BitsPerSampleClient, m_Config.ChannelsClient);
                                //Abspielen
                                m_PlayerClient.PlayData(linearBytes, false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// InitJitterBuffer
        /// </summary>
        private void InitJitterBufferServerRecording()
        {
            //Wenn vorhanden
            if (m_JitterBufferServerRecording != null)
            {
                m_JitterBufferServerRecording.DataAvailable -= new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferServerDataAvailable);
            }

            //Neu erstellen
            m_JitterBufferServerRecording = new WinSound.JitterBuffer(null, 20, 20);
            m_JitterBufferServerRecording.DataAvailable += new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferServerDataAvailable);
        }

        /// <summary>
        /// OnJitterBufferServerDataAvailable
        /// </summary>
        /// <param name="rtp"></param>
        private void OnJitterBufferServerDataAvailable(Object sender, WinSound.RTPPacket rtp)
        {
            try
            {
                if (IsServerRunning)
                {
                    if (m_IsFormMain)
                    {
                        //RTP Packet in Bytes umwandeln
                        Byte[] rtpBytes = rtp.ToBytes();

                        //Für alle Clients
                        List<NF.ServerThread> list = new List<NF.ServerThread>(m_Server.Clients);
                        foreach (NF.ServerThread client in list)
                        {
                            //Wenn nicht Mute
                            if (client.IsMute == false)
                            {
                                try
                                {
                                    //Absenden
                                    client.Send(m_PrototolClient.ToBytes(rtpBytes));
                                }
                                catch (Exception)
                                {
                                    //Eintrag löschen
                                    //RemoveControlInAllFlowLayoutPanelsByServerThread(client);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelServer, ex.Message);
            }
        }

        /// <summary>
        /// DisconnectClient
        /// </summary>
        private void DisconnectClient()
        {
            try
            {
                //Aufnahme beenden
                StopRecordingFromSounddevice_Client();

                if (m_Client != null)
                {
                    //Client beenden
                    m_Client.Disconnect();
                    m_Client.ClientConnected -= new NF.TCPClient.DelegateConnection(OnClientConnected);
                    m_Client.ClientDisconnected -= new NF.TCPClient.DelegateConnection(OnClientDisconnected);
                    m_Client.ExceptionAppeared -= new NF.TCPClient.DelegateException(OnClientExceptionAppeared);
                    m_Client.DataReceived -= new NF.TCPClient.DelegateDataReceived(OnClientDataReceived);
                    m_Client = null;
                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// OnClientDataReceived
        /// </summary>
        /// <param name="client"></param>
        /// <param name="bytes"></param>
        private void OnClientDataReceived(NF.TCPClient client, Byte[] bytes)
        {
            try
            {
                if (m_PrototolClient != null)
                {
                    m_PrototolClient.Receive_LH(client, bytes);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// OnClientExceptionAppeared
        /// </summary>
        /// <param name="client"></param>
        /// <param name="ex"></param>
        private void OnClientExceptionAppeared(NF.TCPClient client, Exception ex)
        {
            DisconnectClient();
            //ShowError(LabelClient, ex.Message);
        }

        /// <summary>
        /// OnClientDisconnected
        /// </summary>
        /// <param name="client"></param>
        /// <param name="info"></param>
        private void OnClientDisconnected(NF.TCPClient client, string info)
        {
            //Abspielen beenden
            StopPlayingToSounddevice_Client();
            //Streamen von Sounddevice beenden
            StopRecordingFromSounddevice_Client();

            if (m_Client != null)
            {
                m_Client.ClientConnected -= new NF.TCPClient.DelegateConnection(OnClientConnected);
                m_Client.ClientDisconnected -= new NF.TCPClient.DelegateConnection(OnClientDisconnected);
                m_Client.ExceptionAppeared -= new NF.TCPClient.DelegateException(OnClientExceptionAppeared);
                m_Client.DataReceived -= new NF.TCPClient.DelegateDataReceived(OnClientDataReceived);
                //ShowMessage(LabelClient, String.Format("Client disconnected {0}", ""));
            }

            ShowClientDisconnected();
        }

        /// <summary>
        /// ShowClientDisconnected
        /// </summary>
        private void ShowClientDisconnected()
        {
            //try
            //{
            //    this.Invoke(new MethodInvoker(delegate()
            //    {
            //        ButtonClient.BackColor = Color.Gray;
            //        TextBoxClientAddress.Enabled = true;
            //        TextBoxClientPort.Enabled = true;
            //        ComboboxSamplesPerSecond.Enabled = true;
            //        NumericUpDownJitterBufferClient.Enabled = true;
            //        ComboboxOutputSoundDeviceNameClient.Enabled = true;
            //        ComboboxInputSoundDeviceNameClient.Enabled = true;
            //        ProgressBarPlayingClient.Visible = false;
            //    }));
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}
        }

        /// <summary>
        /// StopPlayingToSounddevice_Client
        /// </summary>
        private void StopPlayingToSounddevice_Client()
        {
            if (m_PlayerClient != null)
            {
                m_PlayerClient.Close();
                m_PlayerClient = null;
            }

            //JitterBuffer beenden
            if (m_JitterBufferClientPlaying != null)
            {
                m_JitterBufferClientPlaying.Stop();
            }

            //Timer beenden
            m_TimerProgressBarPlayingClient.Stop();

            //Anzeigen
            //this.Invoke(new MethodInvoker(delegate()
            //{
            //    ComboboxOutputSoundDeviceNameClient.Enabled = true;
            //    NumericUpDownJitterBufferClient.Enabled = true;
            //    ProgressBarPlayingClient.Value = 0;
            //}));
        }

        /// <summary>
        /// OnClientConnected
        /// </summary>
        /// <param name="client"></param>
        /// <param name="info"></param>
        private void OnClientConnected(NF.TCPClient client, string info)
        {
            StartPlayingToSounddevice_Client();
        }

        /// <summary>
        /// StartPlayingToSounddevice_Client
        /// </summary>
        private void StartPlayingToSounddevice_Client()
        {
            //Wenn gewünscht
            if (IsPlayingToSoundDeviceWanted)
            {
                //JitterBuffer starten
                if (m_JitterBufferClientPlaying != null)
                {
                    InitJitterBufferClientPlaying();
                    m_JitterBufferClientPlaying.Start();
                }

                if (m_PlayerClient == null)
                {
                    m_PlayerClient = new WinSound.Player();
                    m_PlayerClient.Open(m_Config.SoundOutputDeviceNameClient, m_Config.SamplesPerSecondClient, m_Config.BitsPerSampleClient, m_Config.ChannelsClient, (int)m_Config.JitterBufferCountClient);
                }

                //Timer starten
                m_TimerProgressBarPlayingClient.Start();

            }

            ////Anzeigen
            //ComboboxOutputSoundDeviceNameClient.Invoke(new MethodInvoker(delegate()
            //{
            //    ComboboxOutputSoundDeviceNameClient.Enabled = false;
            //    NumericUpDownJitterBufferClient.Enabled = false;
            //    //ProgressBarPlayingClient.Maximum = (int)m_JitterBufferClientPlaying.Maximum;
            //}));

        }

        /// <summary>
        /// StopRecordingFromSounddevice_Server
        /// </summary>
        private void StopRecordingFromSounddevice_Server()
        {
            try
            {
                if (IsRecorderFromSounddeviceStarted_Server)
                {
                    //Stoppen
                    m_Recorder_Server.Stop();

                    //Events entfernen
                    m_Recorder_Server.DataRecorded -= new WinSound.Recorder.DelegateDataRecorded(OnDataReceivedFromSoundcard_Server);
                    m_Recorder_Server.RecordingStopped -= new WinSound.Recorder.DelegateStopped(OnRecordingStopped_Server);
                    m_Recorder_Server = null;

                    //JitterBuffer beenden
                    m_JitterBufferServerRecording.Stop();

                    //Anzeigen
                    ShowStreamingFromSounddeviceStopped_Server();
                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// ShowStreamingFromSounddeviceStopped_Server
        /// </summary>
        private void ShowStreamingFromSounddeviceStopped_Server()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        ShowStreamingFromSounddeviceStopped_Server();
                    }));
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// OnRecordingStopped_Server
        /// </summary>
        private void OnRecordingStopped_Server()
        {
            try
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    //Anzeigen
                    ShowStreamingFromSounddeviceStopped_Server();

                }));
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// OnDataReceivedFromSoundcard_Server
        /// </summary>
        /// <param name="data"></param>
        private void OnDataReceivedFromSoundcard_Server(Byte[] data)
        {
            try
            {
                lock (this)
                {
                    if (IsServerRunning)
                    {
                        //Wenn Form noch aktiv
                        if (m_IsFormMain)
                        {
                            //Wenn gewünscht
                            if (m_Config.ServerNoSpeakAll == false)
                            {
                                //Sounddaten in kleinere Einzelteile zerlegen
                                int bytesPerInterval = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondServer, m_Config.BitsPerSampleServer, m_Config.ChannelsServer);
                                int count = data.Length / bytesPerInterval;
                                int currentPos = 0;
                                for (int i = 0; i < count; i++)
                                {
                                    //Teilstück in RTP Packet umwandeln
                                    Byte[] partBytes = new Byte[bytesPerInterval];
                                    Array.Copy(data, currentPos, partBytes, 0, bytesPerInterval);
                                    currentPos += bytesPerInterval;
                                    WinSound.RTPPacket rtp = ToRTPPacket(partBytes, m_Config.BitsPerSampleServer, m_Config.ChannelsServer);

                                    //Wenn JitterBuffer
                                    if (UseJitterBufferServerRecording)
                                    {
                                        //In Buffer legen
                                        m_JitterBufferServerRecording.AddData(rtp);
                                    }
                                    else
                                    {
                                        //RTP Packet in Bytes umwandeln
                                        Byte[] rtpBytes = rtp.ToBytes();

                                        //Für alle Clients
                                        foreach (NF.ServerThread client in m_Server.Clients)
                                        {
                                            //Wenn nicht Mute
                                            if (client.IsMute == false)
                                            {
                                                //Absenden
                                                client.Send(m_PrototolClient.ToBytes(rtpBytes));
                                            }
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// ToRTPData
        /// </summary>
        /// <param name="linearData"></param>
        /// <param name="bitsPerSample"></param>
        /// <param name="channels"></param>
        /// <returns></returns>
        private Byte[] ToRTPData(Byte[] data, int bitsPerSample, int channels)
        {
            //Neues RTP Packet erstellen
            WinSound.RTPPacket rtp = ToRTPPacket(data, bitsPerSample, channels);
            //RTPHeader in Bytes erstellen
            Byte[] rtpBytes = rtp.ToBytes();
            //Fertig
            return rtpBytes;
        }
        /// <summary>
        /// ToRTPPacket
        /// </summary>
        /// <param name="linearData"></param>
        /// <param name="bitsPerSample"></param>
        /// <param name="channels"></param>
        /// <returns></returns>
        private WinSound.RTPPacket ToRTPPacket(Byte[] linearData, int bitsPerSample, int channels)
        {
            //Daten Nach MuLaw umwandeln
            Byte[] mulaws = WinSound.Utils.LinearToMulaw(linearData, bitsPerSample, channels);

            //Neues RTP Packet erstellen
            WinSound.RTPPacket rtp = new WinSound.RTPPacket();

            //Werte übernehmen
            rtp.Data = mulaws;
            rtp.CSRCCount = m_CSRCCount;
            rtp.Extension = m_Extension;
            rtp.HeaderLength = WinSound.RTPPacket.MinHeaderLength;
            rtp.Marker = m_Marker;
            rtp.Padding = m_Padding;
            rtp.PayloadType = m_PayloadType;
            rtp.Version = m_Version;
            rtp.SourceId = m_SourceId;

            //RTP Header aktualisieren
            try
            {
                rtp.SequenceNumber = Convert.ToUInt16(m_SequenceNumber);
                m_SequenceNumber++;
            }
            catch (Exception)
            {
                m_SequenceNumber = 0;
            }
            try
            {
                rtp.Timestamp = Convert.ToUInt32(m_TimeStamp);
                m_TimeStamp += mulaws.Length;
            }
            catch (Exception)
            {
                m_TimeStamp = 0;
            }

            //Fertig
            return rtp;
        }

        /// <summary>
        /// 验证IP是否在线
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        private bool VaildIP(string ip)
        {
            Ping pingSender = new Ping();
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 1000;
            PingOptions options = new PingOptions();
            options.DontFragment = true;
            PingReply reply = pingSender.Send(ip, timeout, buffer, options);
            return reply.Status == IPStatus.Success;
        }

        ///// <summary>
        ///// ConnectClient
        ///// </summary>
        private void ConnectClient()
        {
            try
            {
                if (IsClientConnected == false)
                {
                    //Wenn Eingabe vorhanden
                    if (m_Config.IpAddressClient.Length > 0 && m_Config.PortClient > 0)
                    {
                        m_Client = new NF.TCPClient(m_Config.IpAddressClient, m_Config.PortClient);
                        m_Client.ClientConnected += new NF.TCPClient.DelegateConnection(OnClientConnected);
                        m_Client.ClientDisconnected += new NF.TCPClient.DelegateConnection(OnClientDisconnected);
                        m_Client.ExceptionAppeared += new NF.TCPClient.DelegateException(OnClientExceptionAppeared);
                        m_Client.DataReceived += new NF.TCPClient.DelegateDataReceived(OnClientDataReceived);
                        m_Client.Connect();
                    }
                }
            }
            catch (Exception ex)
            {
                m_Client = null;
                //ShowError(LabelClient, ex.Message);
            }
        }

        ///// <summary>
        ///// 开启客户端的服务
        ///// </summary>
        public bool ClientStart()
        {
            bool reValue = false;
            try
            {
                //Daten holen
                //FormToClientConfig();
                LoadConfig();

                if (IsClientConnected)
                {
                    DisconnectClient();
                    StopRecordingFromSounddevice_Client();
                }
                else
                {
                    ConnectClient();
                    StartRecordingFromSounddevice_Client();
                    reValue = true;
                }
                //Kurz warten
                System.Threading.Thread.Sleep(100);

            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
            return reValue;
        }

        private void StartRecordingFromSounddevice_Client()
        {
            try
            {
                if (IsRecorderFromSounddeviceStarted_Client == false)
                {
                    //Buffer Grösse berechnen
                    int bufferSize = 0;
                    if (UseJitterBufferClientRecording)
                    {
                        bufferSize = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondClient, m_Config.BitsPerSampleClient, m_Config.ChannelsClient) * (int)m_RecorderFactor;
                    }
                    else
                    {
                        bufferSize = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondClient, m_Config.BitsPerSampleClient, m_Config.ChannelsClient);
                    }

                    //Wenn Buffer korrekt
                    if (bufferSize > 0)
                    {
                        //Recorder erstellen
                        m_Recorder_Client = new WinSound.Recorder();

                        //Events hinzufügen
                        m_Recorder_Client.DataRecorded += new WinSound.Recorder.DelegateDataRecorded(OnDataReceivedFromSoundcard_Client);
                        m_Recorder_Client.RecordingStopped += new WinSound.Recorder.DelegateStopped(OnRecordingStopped_Client);

                        //Recorder starten
                        if (m_Recorder_Client.Start(m_Config.SoundInputDeviceNameClient, m_Config.SamplesPerSecondClient, m_Config.BitsPerSampleClient, m_Config.ChannelsClient, m_SoundBufferCount, bufferSize))
                        {
                            //Anzeigen
                            //ShowStreamingFromSounddeviceStarted_Client();

                            //Wenn JitterBuffer
                            if (UseJitterBufferClientRecording)
                            {
                                m_JitterBufferClientRecording.Start();
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        ///// <summary>
        ///// ShowStreamingFromSounddeviceStarted 
        ///// </summary>
        private void ShowStreamingFromSounddeviceStarted_Client()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        ShowStreamingFromSounddeviceStarted_Client();
                    }));
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// ShowStreamingFromSounddeviceStarted_Server
        /// </summary>
        private void ShowStreamingFromSounddeviceStarted_Server()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        ShowStreamingFromSounddeviceStarted_Server();
                    }));
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// StartRecordingFromSounddevice_Server
        /// </summary>
        private void StartRecordingFromSounddevice_Server()
        {
            try
            {
                if (IsRecorderFromSounddeviceStarted_Server == false)
                {
                    //Buffer Grösse berechnen
                    int bufferSize = 0;
                    if (UseJitterBufferServerRecording)
                    {
                        bufferSize = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondServer, m_Config.BitsPerSampleServer, m_Config.ChannelsServer) * (int)m_RecorderFactor;
                    }
                    else
                    {
                        bufferSize = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondServer, m_Config.BitsPerSampleServer, m_Config.ChannelsServer);
                    }

                    //Wenn Buffer korrekt
                    if (bufferSize > 0)
                    {
                        //Recorder erstellen
                        m_Recorder_Server = new WinSound.Recorder();

                        //Events hinzufügen
                        m_Recorder_Server.DataRecorded += new WinSound.Recorder.DelegateDataRecorded(OnDataReceivedFromSoundcard_Server);
                        m_Recorder_Server.RecordingStopped += new WinSound.Recorder.DelegateStopped(OnRecordingStopped_Server);

                        //Recorder starten
                        if (m_Recorder_Server.Start(m_Config.SoundInputDeviceNameServer, m_Config.SamplesPerSecondServer, m_Config.BitsPerSampleServer, m_Config.ChannelsServer, m_SoundBufferCount, bufferSize))
                        {
                            //Anzeigen
                            ShowStreamingFromSounddeviceStarted_Server();

                            //JitterBuffer starten
                            m_JitterBufferServerRecording.Start();
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// StartServer
        /// </summary>
        private void StartServer()
        {
            try
            {
                if (IsServerRunning == false)
                {
                    if (m_Config.IPAddressServer.Length > 0 && m_Config.PortServer > 0)
                    {
                        m_Server = new NF.TCPServer();
                        m_Server.ClientConnected += new NF.TCPServer.DelegateClientConnected(OnServerClientConnected);
                        m_Server.ClientDisconnected += new NF.TCPServer.DelegateClientDisconnected(OnServerClientDisconnected);
                        m_Server.DataReceived += new NF.TCPServer.DelegateDataReceived(OnServerDataReceived);
                        m_Server.Start(m_Config.IPAddressServer, m_Config.PortServer);

                        //Je nach Server Status
                        //if (m_Server.State == NF.TCPServer.ListenerState.Started)
                        //{
                        //    ShowServerStarted();
                        //}
                        //else
                        //{
                        //    ShowServerStopped();
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelServer, ex.Message);
            }
        }


        /// <summary>
        /// StopServer
        /// </summary>
        private void StopServer()
        {
            try
            {
                if (IsServerRunning == true)
                {

                    //Player beenden
                    DeleteAllServerThreadDatas();

                    //Server beenden
                    m_Server.Stop();
                    m_Server.ClientConnected -= new NF.TCPServer.DelegateClientConnected(OnServerClientConnected);
                    m_Server.ClientDisconnected -= new NF.TCPServer.DelegateClientDisconnected(OnServerClientDisconnected);
                    m_Server.DataReceived -= new NF.TCPServer.DelegateDataReceived(OnServerDataReceived);
                }

                //Je nach Server Status
                //if (m_Server != null)
                //{
                //    if (m_Server.State == NF.TCPServer.ListenerState.Started)
                //    {
                //        ShowServerStarted();
                //    }
                //    else
                //    {
                //        ShowServerStopped();
                //    }
                //}

                //Fertig
                m_Server = null;
            }
            catch (Exception ex)
            {
                //ShowError(LabelServer, ex.Message);
            }
        }

        /// <summary>
        /// OnServerDataReceived
        /// </summary>
        /// <param name="st"></param>
        /// <param name="data"></param>
        private void OnServerDataReceived(NF.ServerThread st, Byte[] data)
        {
            //Wenn vorhanden
            if (m_DictionaryServerDatas.ContainsKey(st))
            {
                //Wenn Protocol
                ServerThreadData stData = m_DictionaryServerDatas[st];
                if (stData.Protocol != null)
                {
                    stData.Protocol.Receive_LH(st, data);
                }
            }
        }

        /// <summary>
        /// OnServerClientDisconnected
        /// </summary>
        /// <param name="st"></param>
        /// <param name="info"></param>
        private void OnServerClientDisconnected(NF.ServerThread st, string info)
        {
            try
            {
                //Wenn vorhanden
                if (m_DictionaryServerDatas.ContainsKey(st))
                {
                    //Alle Daten freigeben
                    ServerThreadData data = m_DictionaryServerDatas[st];
                    data.Dispose();
                    lock (LockerDictionary)
                    {
                        //Entfernen
                        m_DictionaryServerDatas.Remove(st);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// DeleteAllServerThreadDatas
        /// </summary>
        private void DeleteAllServerThreadDatas()
        {
            lock (LockerDictionary)
            {
                try
                {
                    foreach (ServerThreadData info in m_DictionaryServerDatas.Values)
                    {
                        info.Dispose();
                    }
                    m_DictionaryServerDatas.Clear();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        /// <summary>
        /// OnServerClientConnected
        /// </summary>
        /// <param name="st"></param>
        private void OnServerClientConnected(NF.ServerThread st)
        {
            try
            {
                //ServerThread Daten erstellen
                ServerThreadData data = new ServerThreadData();
                //Initialisieren
                data.Init(st, m_Config.SoundOutputDeviceNameServer, m_Config.SamplesPerSecondServer, m_Config.BitsPerSampleServer, m_Config.ChannelsServer, m_SoundBufferCount, m_Config.JitterBufferCountServer, m_Milliseconds);
                //Hinzufügen
                m_DictionaryServerDatas[st] = data;
                //Zu FlowLayoutPanels hinzufügen
                //AddServerClientToFlowLayoutPanel_ServerClient(st);
                //AddServerClientToFlowLayoutPanel_ServerProgressBars(data);
                //AddServerClientToFlowLayoutPanel_ServerListenButtons(data);
                //AddServerClientToFlowLayoutPanel_ServerSpeakButtons(data);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// StopRecordingFromSounddevice_Client
        /// </summary>
        private void StopRecordingFromSounddevice_Client()
        {
            try
            {
                if (IsRecorderFromSounddeviceStarted_Client)
                {
                    //Stoppen
                    m_Recorder_Client.Stop();

                    //Events entfernen
                    m_Recorder_Client.DataRecorded -= new WinSound.Recorder.DelegateDataRecorded(OnDataReceivedFromSoundcard_Client);
                    m_Recorder_Client.RecordingStopped -= new WinSound.Recorder.DelegateStopped(OnRecordingStopped_Client);
                    m_Recorder_Client = null;

                    //Wenn JitterBuffer
                    if (UseJitterBufferClientRecording)
                    {
                        m_JitterBufferClientRecording.Stop();
                    }

                    //Anzeigen
                    ShowStreamingFromSounddeviceStopped_Client();
                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// OnRecordingStopped
        /// </summary>
        private void OnRecordingStopped_Client()
        {
            try
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    //Anzeigen
                    ShowStreamingFromSounddeviceStopped_Client();

                }));
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// ShowStreamingFromSounddeviceStopped_Client 
        /// </summary>
        private void ShowStreamingFromSounddeviceStopped_Client()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        ShowStreamingFromSounddeviceStopped_Client();
                    }));
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                //ShowError(LabelClient, ex.Message);
            }
        }

        /// <summary>
        /// OnDataReceivedFromSoundcard_Client
        /// </summary>
        /// <param name="linearData"></param>
        private void OnDataReceivedFromSoundcard_Client(Byte[] data)
        {
            try
            {
                lock (this)
                {
                    if (IsClientConnected)
                    {
                        //Wenn gewünscht
                        if (m_Config.ClientNoSpeakAll == false)
                        {
                            //Sounddaten in kleinere Einzelteile zerlegen
                            int bytesPerInterval = WinSound.Utils.GetBytesPerInterval((uint)m_Config.SamplesPerSecondClient, m_Config.BitsPerSampleClient, m_Config.ChannelsClient);
                            int count = data.Length / bytesPerInterval;
                            int currentPos = 0;
                            for (int i = 0; i < count; i++)
                            {
                                //Teilstück in RTP Packet umwandeln
                                Byte[] partBytes = new Byte[bytesPerInterval];
                                Array.Copy(data, currentPos, partBytes, 0, bytesPerInterval);
                                currentPos += bytesPerInterval;
                                WinSound.RTPPacket rtp = ToRTPPacket(partBytes, m_Config.BitsPerSampleClient, m_Config.ChannelsClient);

                                //Wenn JitterBuffer
                                if (UseJitterBufferClientRecording)
                                {
                                    //In Buffer legen
                                    m_JitterBufferClientRecording.AddData(rtp);
                                }
                                else
                                {
                                    //Alles in RTP Packet umwandeln
                                    Byte[] rtpBytes = ToRTPData(data, m_Config.BitsPerSampleClient, m_Config.ChannelsClient);
                                    //Absenden
                                    m_Client.Send(m_PrototolClient.ToBytes(rtpBytes));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }


        #endregion

        #endregion
        #endregion

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                #region 关闭广播
                //Form ist geschlossen
                m_IsFormMain = false;

                //Aufnahme beenden
                StopRecordingFromSounddevice_Server();
                //Streamen von Sounddevice beenden
                StopRecordingFromSounddevice_Client();
                //Client beenden
                DisconnectClient();
                //Server beenden
                StopServer();
                #endregion
                Thread.CurrentThread.IsBackground = true;
                #region 关闭点对点中UDP所占用的资源
                if (m_pUdpServer != null)
                {
                    m_pUdpServer.Dispose();
                    m_pUdpServer = null;
                }
                if (m_pWaveIn != null)
                {
                    m_pWaveIn.Dispose();
                    m_pWaveIn = null;
                }
                if (m_pWaveOut != null)
                {
                    m_pWaveOut.Dispose();
                    m_pWaveOut = null;
                }
                tmpThread.Abort();
                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

   




    }

    #region 配置文件和服务器线程数据
    /// <summary>
    /// Config
    /// </summary>
    public class Configuration
    {
        /// <summary>
        /// Config
        /// </summary>
        public Configuration()
        {

        }

        //Attribute
        public String IpAddressClient = "";
        public String IPAddressServer = "";
        public int PortClient = 0;
        public int PortServer = 0;
        public String SoundInputDeviceNameClient = "";
        public String SoundOutputDeviceNameClient = "";
        public String SoundInputDeviceNameServer = "";
        public String SoundOutputDeviceNameServer = "";
        public int SamplesPerSecondClient = 8000;
        public int BitsPerSampleClient = 16;
        public int ChannelsClient = 1;
        public int SamplesPerSecondServer = 8000;
        public int BitsPerSampleServer = 16;
        public int ChannelsServer = 1;
        public bool UseJitterBufferClientRecording = true;
        public bool UseJitterBufferServerRecording = true;
        public uint JitterBufferCountServer = 20;
        public uint JitterBufferCountClient = 20;
        public string FileName = "";
        public bool LoopFile = false;
        public bool MuteClientPlaying = false;
        public bool ServerNoSpeakAll = false;
        public bool ClientNoSpeakAll = false;
        public bool MuteServerListen = false;
        public String SelfIp = "";
    }
    /// <summary>
    /// ServerThreadData
    /// </summary>
    public class ServerThreadData
    {
        /// <summary>
        /// Konstruktor
        /// </summary>
        public ServerThreadData()
        {

        }

        //Attribute
        public NF.ServerThread ServerThread;
        public WinSound.Player Player;
        public WinSound.JitterBuffer JitterBuffer;
        public WinSound.Protocol Protocol;
        public int SamplesPerSecond = 8000;
        public int BitsPerSample = 16;
        public int SoundBufferCount = 8;
        public uint JitterBufferCount = 20;
        public uint JitterBufferMilliseconds = 20;
        public int Channels = 1;
        private bool IsInitialized = false;
        public bool IsMute = false;
        public static bool IsMuteAll = false;

        /// <summary>
        /// Init
        /// </summary>
        /// <param name="bitsPerSample"></param>
        /// <param name="channels"></param>
        public void Init(NF.ServerThread st, string soundDeviceName, int samplesPerSecond, int bitsPerSample, int channels, int soundBufferCount, uint jitterBufferCount, uint jitterBufferMilliseconds)
        {
            //Werte übernehmen
            this.ServerThread = st;
            this.SamplesPerSecond = samplesPerSecond;
            this.BitsPerSample = bitsPerSample;
            this.Channels = channels;
            this.SoundBufferCount = soundBufferCount;
            this.JitterBufferCount = jitterBufferCount;
            this.JitterBufferMilliseconds = jitterBufferMilliseconds;

            //Player
            this.Player = new WinSound.Player();
            this.Player.Open(soundDeviceName, samplesPerSecond, bitsPerSample, channels, soundBufferCount);

            //Wenn ein JitterBuffer verwendet werden soll
            if (jitterBufferCount >= 2)
            {
                //Neuen JitterBuffer erstellen
                this.JitterBuffer = new WinSound.JitterBuffer(this.Player, jitterBufferCount, jitterBufferMilliseconds);
                this.JitterBuffer.DataAvailable += new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferDataAvailable);
                this.JitterBuffer.Start();
            }

            //Protocol
            this.Protocol = new WinSound.Protocol(WinSound.ProtocolTypes.LH, Encoding.Default);
            this.Protocol.DataComplete += new WinSound.Protocol.DelegateDataComplete(OnProtocolDataComplete);


            //Initialisiert
            IsInitialized = true;
        }
        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            //Protocol
            if (Protocol != null)
            {
                this.Protocol.DataComplete -= new WinSound.Protocol.DelegateDataComplete(OnProtocolDataComplete);
                this.Protocol = null;
            }

            //JitterBuffer
            if (JitterBuffer != null)
            {
                JitterBuffer.Stop();
                JitterBuffer.DataAvailable -= new WinSound.JitterBuffer.DelegateDataAvailable(OnJitterBufferDataAvailable);
                this.JitterBuffer = null;
            }

            //Player
            if (Player != null)
            {
                Player.Close();
                this.Player = null;
            }

            //Nicht initialisiert
            IsInitialized = false;
        }
        /// <summary>
        /// OnProtocolDataComplete
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        private void OnProtocolDataComplete(Object sender, Byte[] bytes)
        {
            //Wenn initialisiert
            if (IsInitialized)
            {
                if (ServerThread != null && Player != null)
                {
                    try
                    {
                        //Wenn der Player gestartet wurde
                        if (Player.Opened)
                        {

                            //RTP Header auslesen
                            WinSound.RTPPacket rtp = new WinSound.RTPPacket(bytes);

                            //Wenn Header korrekt
                            if (rtp.Data != null)
                            {
                                //Wenn JitterBuffer verwendet werden soll
                                if (JitterBuffer != null && JitterBuffer.Maximum >= 2)
                                {
                                    JitterBuffer.AddData(rtp);
                                }
                                else
                                {
                                    //Wenn kein Mute
                                    if (IsMuteAll == false && IsMute == false)
                                    {
                                        //Nach Linear umwandeln
                                        Byte[] linearBytes = WinSound.Utils.MuLawToLinear(rtp.Data, this.BitsPerSample, this.Channels);
                                        //Abspielen
                                        Player.PlayData(linearBytes, false);
                                    }
                                }
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        IsInitialized = false;
                    }
                }
            }
        }
        /// <summary>
        /// OnJitterBufferDataAvailable
        /// </summary>
        /// <param name="packet"></param>
        private void OnJitterBufferDataAvailable(Object sender, WinSound.RTPPacket rtp)
        {
            if (Player != null)
            {
                //Wenn kein Mute
                if (IsMuteAll == false && IsMute == false)
                {
                    //Nach Linear umwandeln
                    Byte[] linearBytes = WinSound.Utils.MuLawToLinear(rtp.Data, BitsPerSample, Channels);
                    //Abspielen
                    Player.PlayData(linearBytes, false);
                }
            }
        }
    }
    #endregion

}
